﻿using FreeSql;
using IcIntegration.Job.Jobs;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Msung.Core;
using Msung.Core.Caching;
using Msung.Core.Model;
using Msung.Repository.Entity;
using StackExchange.Redis;
using System.Diagnostics.Metrics;

namespace ExceptionDataStatisticsService.Service
{
    public class ExceptionDataService
    {
        private readonly ILogger _logger;
        private readonly IServiceProvider _serviceProvider;

        public ExceptionDataService(
            IServiceProvider serviceProvider,
            ILogger logger)
        {
            _logger = logger;
            _serviceProvider = serviceProvider;
        }
        public void ExceptionDataStatistics(string jobName, string[] equipmentList)
        {
            _logger.LogDebug($"统计异常数据：{jobName}-{DateTime.Now.ToString("yyyy-MM-dd HH:mi:ss")}");
            JobOption? jobOption = AppSetting.JobOptions.FirstOrDefault(m => m.Key == jobName);
            string? redisKey = jobOption?.RedisKey;
            int sqlQty = jobOption == null ? 5 : jobOption.Qty;
            if (string.IsNullOrWhiteSpace(redisKey)) return;

            using (var scope = _serviceProvider.CreateScope())
            {
                try
                {
                    var _freeSqlCloud = scope.ServiceProvider.GetRequiredService<FreeSqlCloud<string>>();
                    var _freesql = _freeSqlCloud.Change("TRACER");
                    var ado = _freesql.Ado;
                    string dataTime = GetDateHour(jobName);
                    DateTime currentTime = DateTime.Parse(dataTime);
                    if (currentTime.Hour == DateTime.Now.Hour && currentTime.Day == DateTime.Now.Day) return;

                    string time = GetTime(jobName, currentTime);
                    string[] times = time.Split(',');
                    dataTime = currentTime.AddHours(1).ToString("yyyy-MM-dd HH:00:00");
                    SaveHour(jobName, dataTime);
                    foreach (var item in equipmentList)
                    {
                        string sql = "select Id,ProcessId,EquipmentId,WaferId,TestId,DefectName,CreatedTime" +
                        $" from TBL_EXCEPTION_PROCESSDATA where CreatedTime between to_date('{times[0]}','yyyy-mm-dd hh24:mi:ss')" +
                        $" and to_date('{times[1]}','yyyy-mm-dd hh24:mi:ss') and equipmentId = '{item}'";
                        var processIvDataList = ado.Query<TBL_EXCEPTION_PROCESSDATA>(sql);
                        if (processIvDataList.Count > 0)
                        {
                            SaveExceptionStatistics(processIvDataList, redisKey);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message + "\r\n" + ex.StackTrace);
                }
            }
        }

        /// <summary>
        /// 保存HALM小时统计数据
        /// </summary>
        /// <param name="equipmentModels"></param>
        private void SaveExceptionStatistics(List<TBL_EXCEPTION_PROCESSDATA> equipmentModels, string redisKey)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                try
                {
                    var _freeSqlCloud = scope.ServiceProvider.GetRequiredService<FreeSqlCloud<string>>();
                    var _freesql = _freeSqlCloud.Change("TRACER");
                    var _redisRepository = scope.ServiceProvider.GetRequiredService<IRedisOperationRepository>();

                    var equipmentExceptionDataList = equipmentModels.GroupBy(m => new { m.PROCESSID, m.EQUIPMENTID, m.DEFECTNAME })
                        .Select(m => new { m.Key.PROCESSID, m.Key.EQUIPMENTID, m.Key.DEFECTNAME, Qty = m.Count() });
                    foreach (var item in equipmentExceptionDataList)
                    {
                        TBL_EXCEPTION_STATISTICS exceptionData = new TBL_EXCEPTION_STATISTICS()
                        {
                            PROCESSID = item.PROCESSID,
                            EQUIPMENTID = item.EQUIPMENTID,
                            DEFECTNAME = item.DEFECTNAME,
                            QTY = item.Qty,
                            CREATEDTIME = equipmentModels.First().CREATEDTIME
                        };
                        string sql = _freesql.Insert<TBL_EXCEPTION_STATISTICS>(exceptionData).ToSql();
                        _redisRepository.ListLeftPush(redisKey, sql);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message + "\r\n" + ex.StackTrace);
                }
            }
        }



        private string GetTime(string jobName, DateTime dataTime)
        {
            string time = "";
            switch (jobName)
            {
                case "ZrJobService":
                    time = $"{dataTime.AddHours(-11).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-10).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "PkJobService":
                    time = $"{dataTime.AddHours(-10).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-9).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "ThJobService":
                    time = $"{dataTime.AddHours(-9).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-8).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "JpJobService":
                    time = $"{dataTime.AddHours(-8).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-7).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "LpJobService":
                    time = $"{dataTime.AddHours(-7).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-6).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "LkJobService":
                    time = $"{dataTime.AddHours(-6).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-5).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "RcaJobService":
                    time = $"{dataTime.AddHours(-5).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-4).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "AldJobService":
                    time = $"{dataTime.AddHours(-4).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-3).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "ZmJobService":
                    time = $"{dataTime.AddHours(-3).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-2).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "BmJobService":
                    time = $"{dataTime.AddHours(-2).ToString("yyyy-MM-dd HH:00:00")},{dataTime.AddHours(-1).ToString("yyyy-MM-dd HH:00:00")}";
                    break;
                case "IvJobService":
                    time = $"{dataTime.AddHours(-1).ToString("yyyy-MM-dd HH:00:00")},{dataTime.ToString("yyyy-MM-dd HH:00:00")}";
                    break;
            }
            return time;
        }

        /// <summary>
        /// 获取最大ID
        /// </summary>
        /// <param name="equipmentId"></param>
        /// <returns></returns>
        private string GetDateHour(string jobName)
        {
            string time = "";
            try
            {
                if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\Config"))
                {
                    Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Config");
                }

                string filePath = Directory.GetCurrentDirectory() + $"\\Config\\{jobName}.info";
                FileInfo fileInfo = new FileInfo(filePath);
                if (!fileInfo.Exists)
                {
                    //time = $"{DateTime.Now.ToString("yyyy-MM-dd HH:00:00")},{DateTime.Now.AddHours(1).ToString("yyyy-MM-dd HH:00:00")}";
                    time = DateTime.Now.ToString("yyyy-MM-dd HH:00:00");
                    return time;
                }
                StreamReader reader = new StreamReader(filePath);
                string? data = reader.ReadLine();
                reader.Close();
                //DateTime dateTime = DateTime.Parse(data);
                //time = $"{dateTime.ToString("yyyy-MM-dd HH:00:00")},{dateTime.AddHours(1).ToString("yyyy-MM-dd HH:00:00")}";
                time = data;
            }
            catch (Exception ex)
            {
                _logger.LogError($"获取<{jobName}>统计时间失败！\r\n" + ex.Message, ex);
            }
            return time;
        }

        /// <summary>
        /// 保存最大ID
        /// </summary>
        /// <param name="id"></param>
        /// <param name="maxId"></param>
        private void SaveHour(string jobName, string dateTime)
        {
            try
            {
                if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\Config"))
                {
                    Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Config");
                }
                string filePath = Directory.GetCurrentDirectory() + $"\\Config\\{jobName}.info";

                StreamWriter writer = new StreamWriter(filePath);
                writer.Write(dateTime);
                writer.Close();
            }
            catch (Exception ex)
            {
                _logger.LogError($"保存<{jobName}>统计时间失败！\r\n" + ex.Message, ex);
            }
        }
    }
}
